import type { ComponentCode, ComponentDefinition, ComponentDefinitionItem } from '../type'
import { getApiDesignerPlatformComponentProperties, getApiDesignerPlatformComponents } from '@/api/designer/designer'
import { EWebDesignerComponentCategory } from '@/api/designer/model'

export interface ComponentDefinitionMapItem {
  definition: ComponentDefinitionItem
}
/**
 * 组件code到组件定义等信息的映射
 */
const componentDefinitionMap = new Map<ComponentCode, ComponentDefinitionMapItem>([])

const componentDefinitions: Array<ComponentDefinition> = [
  {
    category: EWebDesignerComponentCategory.基础组件,
    icon: 'i-ant-design:account-book-filled',
    text: '基础组件',
    items: [],
  },
  {
    category: EWebDesignerComponentCategory.内容组件,
    icon: 'i-ant-design:account-book-filled',
    text: '内容组件',
    items: [],
  },
  {
    category: EWebDesignerComponentCategory.营销组件,
    icon: 'i-ant-design:account-book-filled',
    text: '营销组件',
    items: [],
  },
]

export interface EntryQuery {
  /**
   * @default '91xuanxiao'
   */
  platform?: string
  pageId?: string
  agencyId?: string
}

/** 页面查询参数 */
const entryQuery: EntryQuery = {
  platform: '91xuanxiao',
}

/**
 * ?platform=91xuanxiao&pageId=1&agencyId=1 
 * 
 * pageId 页面 ID
 *
 * agencyId  机构 ID
 * 
 * @example
 * ?agencyId=1000000&pageId=0
 *
 * 现在使用真实的机构数据进行开发了，以下 ID 都可使用。
 * agencyId：1000000，1000001，1000002
 * pageId：1，2
 */
function getEntryQuery() {
  let query = new URLSearchParams(location.search)

  // 开发环境下，如果没有传入参数，则使用默认环境变量
  if (import.meta.env.DEV && query.size === 0) {
    query = new URLSearchParams(`?platform=${import.meta.env.VITE_APP_MOCK_PLATFORM}&pageId=${import.meta.env.VITE_APP_MOCK_PAGE_ID}&agencyId=${import.meta.env.VITE_APP_MOCK_AGENCY_ID}`)
  }

  entryQuery.platform = query.get('platform') ?? entryQuery.platform
  entryQuery.pageId = query.get('pageId') ?? entryQuery.pageId
  entryQuery.agencyId = query.get('agencyId') ?? entryQuery.agencyId
}

function groupComponents(components: ComponentDefinitionItem[]) {
  components.forEach((definition) => {
    const owner = componentDefinitions.find(d => d.category === definition.category)
    if (owner) {
      owner.items.push(definition)
    }
    componentDefinitionMap.set(definition.code!, { definition })
  })
}

export interface ComponentPropertyMapItem<Property = any> {
  property: Property
}

/**
 * 组件code到组件属性等信息的映射
 */
const componentPropertyMap = new Map<ComponentCode, ComponentPropertyMapItem>([])

function setupDesign(callback: () => void) {
  getEntryQuery()
  Promise.all([getApiDesignerPlatformComponents(entryQuery.platform!), getApiDesignerPlatformComponentProperties(entryQuery.platform!, { agencyId: Number(entryQuery.agencyId!) })])
    .then(([comps, properties]) => {
      if (comps) {
        groupComponents(comps as any)
      }
      if (properties) {
        Object.keys(properties).forEach((code) => {
          componentPropertyMap.set(code as unknown as ComponentCode, { property: (properties as any)[code] })
        })
      }
    })
    .finally(callback)
}

export { componentDefinitionMap, componentDefinitions, componentPropertyMap, entryQuery, groupComponents, setupDesign }
